package com.iotechn.unimall.app.api.lease;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.app.config.ezviz.EzvizService;
import com.iotechn.unimall.data.component.CacheComponent;
import com.iotechn.unimall.data.domain.LeaseCategoryDO;
import com.iotechn.unimall.data.domain.LeaseDO;
import com.iotechn.unimall.data.domain.LeaseDetailsDO;
import com.iotechn.unimall.data.mapper.LeaseCategoryMapper;
import com.iotechn.unimall.data.mapper.LeaseDetailsMapper;
import com.iotechn.unimall.data.mapper.LeaseMapper;
import com.iotechn.unimall.data.model.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class LeaseServiceImpl implements LeaseService {

    @Autowired
    private LeaseMapper leaseMapper;
    @Autowired
    private LeaseCategoryMapper leaseCategoryMapper;
    @Autowired
    private LeaseDetailsMapper leaseDetailsMapper;
    @Autowired
    private CacheComponent cacheComponent;
    @Autowired
    private EzvizService ezvizService;

    @Override
    public Page<LeaseDO> list(Integer page, Integer limit, String title, String categoryId) {
        List<LeaseDO> LeaseDO = leaseMapper.selectListByFront(categoryId,(page - 1) * limit, limit);
        Integer count = leaseMapper.selectCount(new EntityWrapper<>());
        return new Page<>(LeaseDO, page, limit, count);
    }

    @Override
    public LeaseDO detail(Integer id){
        LeaseDO leaseDO = leaseMapper.selectByLeaseId(id);
        String accessToken = cacheComponent.getRaw(EzvizService.ACCESS_TOKEN);
        if(StringUtils.isBlank(accessToken)) {
            synchronized (EzvizService.ACCESS_TOKEN){
                if(StringUtils.isBlank(accessToken))
                    ezvizService.refresh();
            }
            accessToken = cacheComponent.getRaw(EzvizService.ACCESS_TOKEN);
        }
        leaseDO.setAccessToken(accessToken);
        Wrapper<LeaseDetailsDO> wrapper = new EntityWrapper<LeaseDetailsDO>()
                .setSqlSelect("MIN(nums) AS nums", "MIN(price) AS price")
                .eq("lease_id",id);
        List<LeaseDetailsDO> list = leaseDetailsMapper.selectList(wrapper);
        if(list==null || list.get(0) == null){
            leaseDO.setLeastNums(0);
            leaseDO.setLowPrice(0);
        }else{
            leaseDO.setLeastNums( list.get(0).getNums());
            leaseDO.setLowPrice(list.get(0).getPrice());
        }
        return leaseDO;
    }

    @Override
    public List<LeaseCategoryDO> categoryList(){
        return leaseCategoryMapper.selectPullDown();
    }

}
